package com.bzxhh.lock;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * list集合线程不安全
 *
 * @author zhenghao
 * @date 2022/10/09
 */
public class ThreadDemo4 {

    public static void main(String[] args) {
        //创建ArrayList集合
//      ArrayList<Object> list = new ArrayList<>();

        //Vector解决
//      Vector<Object> list = new Vector<>();

        //Collections解决
//        List<Object> list = Collections.synchronizedList(new ArrayList<>());

        //CopyOnWriteArrayList解决
//        CopyOnWriteArrayList<Object> list = new CopyOnWriteArrayList<>();
//
//        for (int i = 0; i < 10; i++) {
//            new Thread(() -> {
//                //向集合中添加内容
//                list.add(UUID.randomUUID().toString().substring(0, 8));
//                //从集合中获取内容
//                System.out.println(list);
//            }, String.valueOf(i)).start();
//        }

        /*********************************************/

        //演示HashSet
//        HashSet<String> set = new HashSet<>();

        //CopyOnWriteArraySet解决
//        CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();
//
//        for (int i = 0; i < 10; i++) {
//            new Thread(() -> {
//                //向集合中添加内容
//                set.add(UUID.randomUUID().toString().substring(0, 8));
//                //从集合中获取内容
//                System.out.println(set);
//            }, String.valueOf(i)).start();
//        }

        /*********************************************/

        //演示HashMap
//        HashMap<String, String> map = new HashMap<>();

        //ConcurrentHashMap解决
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();

        for (int i = 0; i < 10; i++) {
            String key = String.valueOf(i);
            new Thread(() -> {
                //向集合中添加内容
                map.put(key, UUID.randomUUID().toString().substring(0, 8));
                //从集合中获取内容
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }
}
